package com.mo.demo.guava;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;

@Slf4j
public class GuavaAutoLoadTest {

    public static void main(String[] args) throws InterruptedException {

        Cache<String, String> cache = CacheBuilder.newBuilder()
                .build();

        final String cacheKey = "key1";

        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                final String name = "线程1";
                log.info(name);
                String value = cache.get(cacheKey, new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        log.info("{} 开始获取数据", name);
                        Thread.sleep(1000);
                        return name+"的处理结果";
                    }
                });
                log.info("{} 执行完毕。获取到的值={}",name,value);
            }
        }).start();

        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                final String name = "线程2";
                log.info(name);
                String value = cache.get(cacheKey, new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        log.info("{} 开始获取数据", name);
                        Thread.sleep(500);
                        return name+"的处理结果";
                    }
                });
                log.info("{} 执行完毕。获取到的值={}",name,value);
            }
        }).start();

        // 输出：
        // 14:01:07.298 [Thread-0] INFO com.mo.demo.guava.GuavaAutoLoadTest - 线程1
        // 14:01:07.298 [Thread-1] INFO com.mo.demo.guava.GuavaAutoLoadTest - 线程2
        // 14:01:07.324 [Thread-0] INFO com.mo.demo.guava.GuavaAutoLoadTest - 线程1 开始获取数据
        // 14:01:08.330 [Thread-1] INFO com.mo.demo.guava.GuavaAutoLoadTest - 线程2 执行完毕。获取到的值=线程1的处理结果
        // 14:01:08.333 [Thread-0] INFO com.mo.demo.guava.GuavaAutoLoadTest - 线程1 执行完毕。获取到的值=线程1的处理结果
    }
}
